<?php
class article_Model_Translation extends Clu_Db_Table_Abstract
{
    //only specify the table name, everything else inherits
	protected $_name = "article_translations";
	protected $_primary = array("original_article_id","language");

	/**
	 * Implements Clu_Db_Table_Abstract
	 */
	public function findByPrimary($a)
	{
		$id = $a['id'];
		$lang = $a['language'];
		
		if (!$id || !$lang)
			return null;
		else
			return $this->fetchRow('original_article_id = ' . $this->getAdapter()->quote($id, 'INTEGER') .
			 						' AND language = ' . $this->getAdapter()->quote($lang, 'STRING'));     
		
	}
	
	public function findTranslatedLanguagesList($id)
	{
	   	$sql = "SELECT language FROM article_translations WHERE original_article_id = $id";
       	$db  = $this->getAdapter() ;
    	return 	$db->fetchAll($sql);
	}
	
	public function insertRaw($data)
	{
		if (array_key_exists('original_article_id',$data))
			$t['original_article_id'] = $data['original_article_id'];
        else if (array_key_exists('id',$data))
			$t['original_article_id'] = $data['id'];
		if (!$t['original_article_id'])
			return false;

		if (array_key_exists('language',$data))
			$t['language'] = $data['language'];
        else if (array_key_exists('id',$data))
			$t['language'] = $data['tolang'];
		if (!$t['language'])
			return false;
			
		$auth = Zend_Auth::getInstance();
	    $t['translate_poster_id'] 	= $auth->getIdentity()->id;
        $t['translate_post_time'] 	= time();	
        $t['title'] = $data['title'];
        $t['keywords'] = $data['keywords'];
    //    $t['statuschange_reason'] = $data['statuschange_reason'];
        $t['body'] = $data['body'];
		return $this->insert($t);	
	}
	
	public function saveRaw($t, $data, $id, $language, $doValidate)
	{
		//URL is something like this: 
		// translate?id=12&to=vi
		//Therefore $request->getParams() might have a different key names
		if ((!$t) && (!$id || !$language) )
	    	return false;
	    else if (!$t)
	       	if (!$t = $this->findByPrimary(array($id, $language)))
	       		return false;

		$data['original_article_id'] = $id;
		$data['language'] = $language;
		$auth = Zend_Auth::getInstance();
	    $data['translate_updater_id']  = $auth->getIdentity()->id;
        $data['translate_update_time'] = time();
			
	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
	    $t->setFromArray($data);
        return $t->save();
	}
}
?>